use std::time::Duration;

use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use tracing::log;

use migration::{Migrator, MigratorTrait};

#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum DatabaseSet {
    DEFAULT,
    TEST,
}

pub async fn establish_connection(url: &str) -> DatabaseConnection {
    let mut opt = ConnectOptions::new(url);
    opt.max_connections(32)
        .min_connections(4)
        .connect_timeout(Duration::from_secs(3))
        .acquire_timeout(Duration::from_secs(3))
        .idle_timeout(Duration::from_secs(3))
        .max_lifetime(Duration::from_secs(3))
        .sqlx_logging(true)
        .sqlx_logging_level(log::LevelFilter::Info)
        .set_schema_search_path("schemas");

    Database::connect(opt).await?
}

pub async fn migrate(url: &str) {
    let connection = Database::connect(url).await?;
    Migrator::up(&connection, None).await?;
}